package org.qloudgen.borg.security;

import org.apache.ibatis.session.SqlSession;
import org.apache.wicket.Session;
import org.apache.wicket.protocol.http.WebSession;
import org.apache.wicket.request.Request;
import org.qloudgen.borg.CommonValues;
import org.qloudgen.borg.beans.UserBean;
import org.qloudgen.borg.metadb.ConfigNames;

public class DilithiumSession extends WebSession {

	private static final long serialVersionUID = 1L;
	private String userNo;
	
	public DilithiumSession(Request request){
		super(request); 
	}

	public int login(UserBean user){
		
		int ret = authenticate(user);
		if (ret == 0) {
			this.userNo = user.getUserNo();
		}
		return ret;
	}
	
	public DilithiumSession session(){  
        return (DilithiumSession)Session.get();  
    }  
      
	private int authenticate(UserBean user) {
		SqlSession sess = CommonValues.factory.openSession();
		String userType = sess.selectOne(ConfigNames.CHECK_USER,user);
		sess.close();
		if (userType == null ) {
			return -1;
		} else if (userType.equals(CommonValues.STATUS_PAUSE)){
			return -2;
		}
		return 0;		
	}

	public boolean isUserLoggedIn() {
		return this.userNo == null ? false : true;
	}
		
	public String getUserNo(){
		return this.userNo;
	}
}
